<?php
namespace Home\Behaviors;

use Utuo\DistributionShopScore;
/**
 * 订单交易成功行为
 * @author song
 */
class DistributionShopOrderCompletedBehavior extends \Think\Behavior {
	
	public function run( &$param ) {
		$order = $param['order'];
		$orderId = $order['id'];
		$surplus = $order['surplus'];
		$cid = $order['cid'];
		
		$distributionShop = D("My/DistributionShop")->getShopConfig( $cid );
		
		/* 代理商发起结算 */
		$status = 0; // 结算状态
		$distributionShopAgentConfig = $distributionShop['agent_shop_config'];
		$settleMode = $distributionShopAgentConfig['settleMode'];
		if ( $settleMode == 1 ) { // 代理手动提现
		    $status = 1; // 自动设置为已结算
		}
		/**
		 * 代理不压货模式结算处理(名额模式)
		 */
		if ( $order["reward_aids"] and $order["reward_bonus_agent"] ) {
    	    $orderTotalBonus = array();
    	    /* 层级返佣 */
    	    $layerBonus = array_combine(explode(',', $order['reward_aids']), explode(',', $order['reward_bonus_agent']));
    	    $layerBonus = array_filter($layerBonus, function($v) { if ( $v === '' ) { return false; } return true; });
    	    foreach ( $layerBonus as $aid => $bonus ) {
    	        $orderTotalBonus[$aid] += $bonus;
    	    }
    	    $settleOrder = array();
    	    foreach ( $orderTotalBonus as $aid => $bonus ) {
    	        $aid == 's' and $aid = 0;
    	        if ( $aid && $bonus > 0 ) {
    	            $settleOrder[] = array(
    	                'cid' => $order['cid'],
    	                'order_id' => $order['id'],
    	                'end_agent' => $aid,
    	                'surplus' => $bonus,
    	                'create_time' => time(),
    	                'status' => $status,
    	            );
    	            if ( $settleMode == 1 ) { // 代理手动提现
    	               $uid = M("Agent")->where(array("id"=>$aid))->getField("wechat_uid");
    	               M("WechatUser")->where(array('id' => array('eq', $uid)))->save(array('bonus' => array('exp', "bonus+{$bonus}"),));
    	            }
    	        }
    	    }
    	    if ($settleOrder) {
    	        M("DistributionShopOrderSettleAccounts")->addAll($settleOrder);
    	    }
        /**
         * 代理压货模式结算处理(非套餐)
         */
		} elseif ( $surplus > 0 ) {
		    if ( $order['agent_id'] ) {
		        M("DistributionShopOrderSettleAccounts")->add(array(
    				'cid' => $order['cid'],
    				'order_id' => $order['id'],
    				'end_agent' => $order['agent_id'],
    				'surplus' => $surplus, // 盈余
    				'create_time' => time(),
    			    'status' => $status,
    			));
		        if ( $settleMode == 1 ) { // 代理手动提现
		           $uid = M("Agent")->where(array("id"=>$aid))->getField("wechat_uid");
    	           M("WechatUser")->where(array('id' => array('eq', $uid)))->save(array('bonus' => array('exp', "bonus+{$bonus}"),));
		        }
		    }
		}
		
		$distributionShopLogic = D("Home/DistributionShop", "Logic");
		
		/* 返购物积分 */
		if ( $order['actual_reward_currency'] ) {
		    $scoreHandle = DistributionShopScore::getInstance("TradeReward", array('cid'=>$order['cid'], 'uid' => $order['uid']));
		    $scoreHandle->exec(array('score'=>$order['actual_reward_currency']));
		}
		
		/* 更新用户产品推广 */
		$distributionShopLogic->updateUserProductPromotion( $order );
		
		/* 用户不同方式佣金结算 */
		if ( isset($distributionShop['currency_config']['opened']) && $distributionShop['currency_config']['opened'] ) { // 商城币已启用
		    if ( isset($distributionShop['reward_bonus_type']) ) {
		        if ( $distributionShop['reward_bonus_type'] == 1 ) { // 返商城币
		            /* 用户积币结算 */
		            $distributionShopLogic->saveCurrency( $order, $distributionShop['currency_config'] );
		        } elseif ( $distributionShop['reward_bonus_type'] == 2 ) { // 返商城币与现金
		            /* 用户积币结算 */
		            $distributionShopLogic->saveCurrency( $order, $distributionShop['currency_config'] );
		            /* 用户佣金结算 */
		            $distributionShopLogic->saveBonus( $order );
		        } else { // 现金
		            /* 用户佣金结算 */
		            $distributionShopLogic->saveBonus( $order );
		        }
		    } else {
		        /* 用户佣金结算 */
		        $distributionShopLogic->saveBonus( $order );
		    }
		} else {
		    /* 用户佣金结算 */
		    $distributionShopLogic->saveBonus( $order );
    	}
		
		/* 捐赠 */
		if ( $distributionShop['donate_on'] ) {
		    $projectId = I('projectId', 0);
		    $distributionShopLogic->donate( $order, $projectId );
		}
		
	}
	
}